<template>
  <view class="profile-edit-page">
    <!-- 使用uni-app内置状态栏处理 -->
    <view class="status-bar"></view>
    <view class="menu-button-class"></view>
    <view class="dark profile-bg-color profile-content">
      <!-- 顶部导航栏 -->
      <personal-nav @saveProfile="saveProfile" />
      <!-- 主要内容区域 -->
      <scroll-view class="content-view" scroll-y @scroll="handleScroll">
        <!-- 头像设置 -->
        <view class="profile-item avatar-item">
          <view class="avatar-container" @click="chooseAvatar">
            <view class="avatar-wrapper">
              <view v-if="userInfo.avatar">
                <image
                  :src="this.baseURL + userInfo.avatar"
                  class="avatar-img"
                  mode="widthFix"
                />
              </view>
              <view v-else class="avatar-upload">
                <i
                  class="iconfont icon-camera"
                  style="font-size: 40px; color: #ccc"
                />
              </view>
            </view>
            <view class="tip-text">点击更换头像</view>
          </view>
        </view>
        <!-- 
      <view>
        <navigator
          :url="
            '/pages/personal/modify-item?item=username&username=' +
            userInfo.username
          "
          >昵称：{{ userInfo.username }}</navigator
        >
        <navigator
          :url="
            '/pages/personal/modify-item?item=douyin_id&douyin_id=' +
            userInfo.douyin_id
          "
          >抖音号{{ userInfo.douyin_id }}</navigator
        >
      </view> 
      -->
        <view class="profile-form-section">
          <uni-forms
            :model="userInfo"
            class="dark-form user-form"
            :rules="rules"
            ref="ruleFormRef"
          >
            <uni-forms-item
              label="昵称 :"
              name="username"
              required
              class="username-item"
            >
              <uni-easyinput
                type="text"
                v-model="userInfo.username"
                placeholder="请输入姓名"
              />
            </uni-forms-item>
            <uni-forms-item label="抖音号 :" name="douyin_id">
              <input type="text" v-model="userInfo.douyin_id" disabled />
            </uni-forms-item>
            <uni-forms-item label="简介 :" name="signature">
              <input type="text" v-model="userInfo.signature" maxlength="200" />
            </uni-forms-item>
            <uni-forms-item label="学校 :" name="school">
              <view class="school-input-box">
                <input type="text" v-model="userInfo.school" />
                <i class="iconfont icon-school" size="24" color="#ccc"></i>
              </view>
            </uni-forms-item>
            <uni-forms-item
              label="性别 :"
              name="gender"
              class="gender-item"
              required
            >
              <uni-data-select
                v-model="userInfo.gender"
                :localdata="genderList"
              >
              </uni-data-select>
            </uni-forms-item>
            <uni-forms-item
              label="生日 :"
              name="birthday"
              class="birthday-item"
              required
            >
              <uni-datetime-picker
                v-model="userInfo.birthday"
                type="date"
                :start="startDate"
                :end="endDate"
                placeholder="请选择日期"
                class="dark-datetime-picker"
                @change="handleDateChange"
              ></uni-datetime-picker>
            </uni-forms-item>
            <uni-forms-item
              label="手机号码 :"
              name="phone"
              required
              class="phone-item"
            >
              <uni-easyinput
                type="text"
                v-model="userInfo.phone"
                placeholder="请输入手机号"
                maxlength="11"
              />
            </uni-forms-item>
            <uni-forms-item label="地区 :" name="city">
              <input type="text" v-model="userInfo.city" />
              <uni-icon type="right" size="18" color="#ccc" />
            </uni-forms-item>
          </uni-forms>
        </view>
      </scroll-view>
    </view>
    <tab />
  </view>
</template>

<script>
  import { citySelectorPage, mePage } from "@/API/pageConst";
  import personalNav from "@/components/personal/personal-nav.vue";
  import tab from "@/components/tab";
  export default {
    components: {
      personalNav,
      tab,
    },
    data() {
      // 自定义手机号验证规则
      const validatePhone = (rule, value, data, callback) => {
        // 中国手机号正则：以1开头，第二位3-9，后面9位数字
        const phoneReg = /^1[3-9]\d{9}$/;
        if (!value || value.trim().length === 0) {
          return callback("请输入手机号");
        } else if (!phoneReg.test(value)) {
          return callback("请输入正确的手机号格式");
        } else {
          return callback();
        }
      };

      return {
        // 用户信息
        userInfo: {
          avatar: "", // 默认头像
          username: "",
          gender: 0, // 0-保密,1-男,2-女
          douyin_id: "",
          birthday: "2024-01-01",
          phone: "",
          signature: "",
          city: "",
        },
        rules: {
          username: {
            rules: [
              {
                required: true,
                errorMessage: "请输入姓名",
              },
            ],
          },
          birthday: {
            rules: [
              {
                required: true,
                errorMessage: "请选择日期",
              },
            ],
          },
          phone: {
            rules: [
              { required: true, errorMessage: "请输入手机号" },
              { validateFunction: validatePhone },
            ],
          },
        },
        // 性别列表
        genderList: [
          { text: "保密", value: 0 },
          { text: "男", value: 1 },
          { text: "女", value: 2 },
        ],

        // 提示消息
        toastMessage: "",
        // locale: zhCn,
      };
    },
    mounted() {
      this.disableCtrlS();
    },
    computed: {
      startDate() {
        const currentDate = new Date();
        const startDate = new Date(currentDate.getFullYear() - 5, 2, 1);
        return startDate.toLocaleDateString();
      },
      endDate() {
        const endDate = new Date();
        return endDate.toLocaleDateString();
      },

      // 性别文本
      genderText() {
        switch (this.userInfo.gender) {
          case 1:
            return "男";
          case 2:
            return "女";
          default:
            return "保密";
        }
      },
    },
    onReady() {
      this.$refs.ruleFormRef.setRules(this.rules);
    },
    onLoad() {
      // 从本地存储或接口获取用户信息
      this.loadUserInfo();
      this.loadCachedUserInfo();
    },

    methods: {
      handleScroll(e) {
        console.log(e);
      },
      // 获取uni缓存中的昵称或者抖音号
      loadCachedUserInfo() {
        uni.getStorage({
          key: "username",
          success: (res) => {
            const username = res.data;
            if (username) {
              this.userInfo.username = username;
            }
          },
        });
        uni.getStorage({
          key: "douyin_id",
          success: (res) => {
            const douyin_id = res.data;
            if (douyin_id) {
              this.userInfo.douyin_id = douyin_id;
            }
          },
        });
      },
      // 日期变化事件
      handleDateChange(e) {
        this.selectedDate = e;
      },
      disableCtrlS() {
        // #ifdef H5
        // 监听键盘按下事件
        document.addEventListener("keydown", function (e) {
          // 判断是否同时按下了 Ctrl+S (Windows/Linux) 或 Cmd+S (Mac)
          if ((e.ctrlKey || e.metaKey) && e.key === "s") {
            e.preventDefault(); // 阻止浏览器默认的保存行为
            e.stopPropagation(); // 阻止事件冒泡
            // 这里什么都不做，达到"Ctrl+S无反应"的效果
          }
        });
        // #endif
      },
      disabledDate(time) {
        const minDate = new Date("1960-01-01");
        const maxDate = new Date();
        return (
          time.getTime() < minDate.getTime() ||
          time.getTime() > maxDate.getTime()
        ); // 返回true表示禁用该日期
      },
      // 保存个人资料
      async saveProfile() {
        this.$refs.ruleFormRef
          .validate()
          .then((res) => {
            uni.showToast({
              title: `信息保存成功`,
            });
            // uni.navigateBack({
            //   delta: 1,
            // });
            uni.switchTab({
              url: mePage,
            });
          })
          .catch((err) => {
            console.log("err", err);
          });
        // 保存到本地存储
        uni.setStorageSync("userInfo", this.userInfo);
        // this.showToast("保存成功");
        // setTimeout(() => {
        //   this.navigateBack();
        // }, 1500);
      },
      switchCity(city) {
        uni.navigateTo({
          url: citySelectorPage,
          success: (res) => {
            const eventChannel = res.eventChannel;
            eventChannel.emit("location-city-event", {
              city,
            });
          },
          events: {
            citySelected: (data) => {
              this.userInfo.city = data.city;
            },
          },
        });
      },
      // 加载用户信息（实际项目中可能从接口获取）
      loadUserInfo() {
        // 模拟从本地存储获取用户信息
        const storedUser = uni.getStorageSync("userInfo");
        if (storedUser) {
          this.userInfo = { ...this.userInfo, ...storedUser };
        }
        // 判断birthday 格式是否为 yyyy-mm-dd,不是就需要转换成yyyy-mm-dd格式
        if (this.userInfo.birthday && this.userInfo.birthday.length !== 10) {
          this.userInfo.birthday = this.userInfo.birthday.split("T")[0];
        }
      },

      // 选择头像
      chooseAvatar(event) {
        event.stopPropagation();
        uni.chooseImage({
          count: 1,
          sizeType: ["original", "compressed"],
          extension: ["jpg", "png", "jpeg", "ico"],
          sourceType: ["album", "camera"],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0];
            console.log("", res.tempFilePaths);
            console.log("tempFilePath,", tempFilePath);
            // 预览头像
            this.userInfo.avatar = tempFilePath;

            // 实际项目中这里应该上传到服务器
            // this.uploadAvatar(tempFilePath);
          },
        });
      },

      // 上传头像（实际项目中实现）
      uploadAvatar(tempFilePath) {
        // 这里是上传逻辑，根据实际后端API进行调整
        /*
      uni.uploadFile({
        url: 'https://your-api.com/upload-avatar',
        filePath: tempFilePath,
        name: 'avatar',
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (data.success) {
            this.userInfo.avatar = data.url;
          }
        }
      });
      */
      },

      // 显示提示消息
      showToast(message) {
        this.toastMessage = message;
        this.$refs.toast.show();
      },

      // 返回上一页
      // navigateBack() {
      //   uni.navigateBack({
      //     delta: 1,
      //   });
      // },
    },
  };
</script>
<style scoped>
  .menu-button-class {
    /* #ifdef H5 */
    height: 0;
    /* #endif */
    /* #ifndef H5 */
    height: 44px;
    /* #endif */
    background-color: var(--o-bg-blue);
  }
  .status-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: var(--status-bar-height, 0);
    background-color: #fff;
    z-index: 999;
  }
  .profile-bg-color {
    background-color: var(--o-bg-blue);
  }
  .profile-content {
    padding-top: var(--status-bar-height, 0);
  }
  .profile-edit-page {
    height: 100vh;
    box-sizing: border-box;
    z-index: 1;
    display: flex;
    flex-direction: column;
    background-color: var(--o-bg-blue);
  }

  .profile-edit-page::-webkit-scrollbar {
    display: none;
  }

  /* 内容区域 */
  .content-view {
    flex: 1;
    overflow-y: auto;
    background-color: var(--o-bg-blue);
    margin: 0 auto;
    color: var(--o-color-stone);
    height: calc(100vh - 150px);
  }
  @media (min-width: 600px) {
    .content-view {
      max-width: 400px;
    }
  }

  .content::-webkit-scrollbar {
    display: none;
  }

  /* 资料项通用样式 */
  .profile-item {
    display: flex;
    align-items: center;
    padding: 14px 16px;
    justify-content: space-between;
  }

  /* 头像设置样式 */
  .avatar-item {
    padding: 20px 16px;
  }

  .avatar-container {
    /* flex: 1; */
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    width: 100px;
    height: 105px;
    margin: 0 auto;
    color: var(--o-color);
  }

  .avatar-wrapper {
    position: relative;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;
    border: 1px solid #808080;
  }

  .avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .avatar-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .scroll-fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 999;
  }

  /* 日期选择器 */
  .date-picker-container {
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    background-color: var(--o-bg-blue);
    color: var(--o-color-stone);
  }

  .date-picker-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    /* border-bottom: 1px solid #eee; */
  }

  .cancel-btn,
  .confirm-btn {
    font-size: 16px;
    padding: 8px 16px;
  }

  .cancel-btn {
    color: #666;
  }

  .confirm-btn {
    color: #007aff;
  }

  .title-text {
    font-size: 18px;
    font-weight: 500;
  }

  .tip-text {
    margin-top: 5px;
  }

  .picker-view {
    width: 100%;
    height: 200px;
    color: #fff;
    background-color: #171827;
  }

  .picker-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    font-size: 16px;
  }

  .time-mask {
    background-image: linear-gradient(180deg, #000000f2, hsla(0, 0%, 2%, 0.6)),
      linear-gradient(0deg, #000000f2, hsla(0, 0%, 3%, 0.6));
  }

  .picker-content {
    touch-action: none;
  }

  .profile-form-section {
    /* 容器背景设为深色 */
    background-color: #171827;
    padding: 8px 16px;
  }

  /* 暗黑主题表单样式 */
  .dark-form {
    /* 表单容器背景 */
    --form-bg-color: #2c2c2c;
    --form-bg-color: #171827;
    /* 标签文字颜色 */
    --label-color: #e0e0e0;
    /* 输入框背景 */
    --input-bg-color: #3a3a3a;
    /* 输入框文字颜色 */
    --input-text-color: #ffffff;
    /* 输入框占位符颜色 */
    --placeholder-color: #888888;
    /* 边框颜色 */
    --border-color: #4a4a4a;
    /* 错误提示颜色 */
    --error-color: #ff5252;
    --input-right-color: #747272;
    --input-border-color: #ebeef5;

    background-color: var(--form-bg-color);
    padding: 30rpx;
    border-radius: 16rpx;
  }

  /* 覆盖uni-forms-item样式 */
  .dark-form >>> .uni-forms-item__label {
    color: var(--label-color);
    width: 100px !important;
  }

  .dark-form >>> uni-input {
    flex: 1;
  }

  .dark-form >>> .uni-forms-item__content {
    display: flex;
    align-items: center;
    padding-left: 10px;
    border: 1px solid var(--input-border-color);
    flex: 1;
  }

  .dark-form >>> .username-item .uni-forms-item__content,
  .dark-form >>> .phone-item .uni-forms-item__content {
    padding: 0;
  }
  .dark-form
    >>> .username-item
    .uni-forms-item__content
    .uni-easyinput__content,
  .dark-form >>> .phone-item .uni-forms-item__content .uni-easyinput__content {
    background-color: var(--form-bg-color) !important;
    color: var(--label-color) !important;
  }
  .dark-form >>> .gender-item .uni-forms-item__content {
    padding: 0;
  }

  .dark-form >>> .gender-item .uni-forms-item__content .uni-stat-box {
    background-color: var(--form-bg-color);
    color: var(--label-color);
  }

  .dark-form >>> .gender-item .uni-stat-box .uni-select__input-text {
    color: var(--label-color);
  }

  .dark-form >>> .gender-item .uni-stat-box .uni-select__selector {
    background-color: var(--form-bg-color);
  }

  .dark-form >>> .birthday-item .uni-forms-item__content {
    padding: 0;
  }

  .school-input-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 1;
  }

  .school-input-box i {
    padding-right: 10px;
  }

  /* 暗黑模式日期选择器样式 */
  .dark-datetime-picker {
    /* 自定义组件变量 - 基础样式 */
    --border-color: #4a4a4a;
    /* 边框颜色 */
    --datetime-background-color: #2c2c2c;
    /* 输入框背景 */
    --text-color: #ffffff;
    /* 文本颜色 */
    --placeholder-color: #888888;
    /* 占位符颜色 */
    --icon-color: #bbbbbb;
    /* 图标颜色 */

    /* 输入框样式 */
    width: 100%;
    border-radius: 8rpx;
  }

  .dark-datetime-picker >>> .uni-date-x {
    background-color: var(--form-bg-color);
    color: var(--label-color);
  }

  .dark-datetime-picker >>> .uni-date-single--x,
  .dark-datetime-picker >>> .uni-calendar {
    background-color: var(--datetime-background-color);
    color: var(--label-color);
  }

  .dark-datetime-picker >>> .uni-date-single--x {
    border: none;
  }

  .dark-datetime-picker >>> .uni-date-picker__container {
    box-sizing: border-box;
  }

  .dark-datetime-picker >>> .uni-date-single--x .uni-popper__arrow:after {
    border-bottom-color: var(--input-right-color);
  }

  /* 穿透修改弹出层样式（日期选择面板） */
  .dark-datetime-picker >>> .uni-date-picker__container {
    background-color: #2c2c2c;
    border-top-color: #4a4a4a;
  }

  /* 标题栏样式 */
  .dark-datetime-picker >>> .uni-calendar__header {
    color: #ffffff;
    border-bottom-color: #4a4a4a;
  }

  .dark-datetime-picker >>> .uni-calendar__header-btn {
    border-left-color: var(--text-color);
    border-top-color: var(--text-color);
  }

  /* 标题文字颜色 */
  .dark-datetime-picker >>> .uni-calendar__header-text {
    color: var(--text-color);
  }

  /* 日期选择器主体样式 */
  .dark-datetime-picker >>> .uni-calendar__content {
    color: var(--text-color);
    background-color: var(--datetime-background-color);
  }

  .dark-datetime-picker >>> .uni-calendar-item__weeks-box-text {
    color: #fff;
  }

  .dark-datetime-picker >>> .uni-calendar-content__day--active {
    background-color: #007aff;
    color: #ffffff;
  }

  .dark-datetime-picker >>> .uni-calendar-item__weeks-box {
    color: #fff;
  }

  /* 禁用日期样式 */
  .dark-datetime-picker
    >>> .uni-calendar-item--disable
    .uni-calendar-item__weeks-box-text-disable {
    color: #666666;
  }
</style>
